package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张杰
 * Date: 2022-04-25
 * Time: 21:13
 */
public class TcpThreadEchoServer {
    private ServerSocket serverSocket = null;

    public TcpThreadEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动  ");
        while(true) {
            //由于TCP是有连接的,不能一上来就读数据,而要建立连接(接电话)
            //accept 如果当前没有客户端尝试连接,此处的accept就会阻塞
            //将建立连接分为两步,一个专门负责建立连接,一个专门负责数据通信
            Socket clientSocket = serverSocket.accept();
            //每次创建成功都创建一个新的线程,新的线程负责执行processConnection 方法
            Thread t = new Thread(() -> {
                processConnection(clientSocket);
            });
            t.start();

        }
    }

    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s:%d] 客户端建立连接!\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        //针对TCP socket的读写和文件读写是一致的
        try (InputStream inputStream = clientSocket.getInputStream()) {
            try(OutputStream outputStream = clientSocket.getOutputStream()) {
                //循环处理每个请求,分别返回响应
                Scanner scanner = new Scanner(inputStream);
                while(true) {
                    //1.读取请求
                    if(!scanner.hasNext()) {
                        System.out.printf("[%s:%d] 客户端断开连接!\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                        break;
                    }
                    String request = scanner.next();
                    // 2.根据请求,计算响应
                    String response = process(request);
                    // 3.把这个响应返回给客户端,使用PrintWriter把OutputStream包裹一下
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(response);
                    printWriter.flush();

                    System.out.printf("[%s:%d] req: %s,resp: %s\n",clientSocket.getInetAddress().toString(),
                            clientSocket.getPort(),request,response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //只需要将客户端程序关闭即可,服务器端的程序不需要进行关闭
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpThreadEchoServer server = new TcpThreadEchoServer(9090);
        server.start();
    }
}
